﻿using AdminSystem.Application.Commands.BreedCommands;
using AdminSystem.Application.Dtos;
using AdminSystem.Domain.Entities;
using AdminSystem.EntityFramworkCore;
using AdminSystem.Repositories.Interfaces;
using AutoMapper;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminSystem.Application.CommandHandlers.BreedCommandHandlers
{
    public class BreedQueryCommandHandler : IRequestHandler<BreedQueryCommand, APIResult<BreedDTO>>
    {
        private readonly IBaseRepositories<Traceability> traceabilityBase;
        private readonly IBaseRepositories<Breed> breedBase;
        public BreedQueryCommandHandler(IBaseRepositories<Traceability> traceabilityBase, IBaseRepositories<Breed> breedBase)
        {
            this.traceabilityBase = traceabilityBase;
            this.breedBase = breedBase;
        }
        public async Task<APIResult<BreedDTO>> Handle(BreedQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<BreedDTO> result = new APIResult<BreedDTO>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var breed = from a in await traceabilityBase.GetAll()
                        join b in await breedBase.GetAll() on a.BreedId equals b.BreedId
                        where a.Id == request.Id
                        select new BreedDTO
                        {
                            BreedId = b.BreedId,
                            Variety = b.Variety,
                            Source = b.Source,
                            FeedingDays = b.FeedingDays,
                            FeedingBrand = b.FeedingBrand,
                            FeedingName = b.FeedingName,
                            SaleDate = b.SaleDate
                        };
            if(breed.Count()== 0)
            {
                result.Code = ResultCode.查询失败;
                result.Message = ResultCode.查询失败.ToString();
                return await Task.FromResult(result);
            }
            result.Data = breed.FirstOrDefault();
            return await Task.FromResult(result);
        }
    }
}
